package chapter15.generator;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Random;

/**
 * @author : DuJiabao
 * @Date : 2021/3/4 11:43
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */
public class CoffeeGenerator implements Generator<Coffee>, Iterable<Coffee> {
  private final Class<?>[] types =
          {Latte.class, Mocha.class, Cappuccino.class, Americano.class, Breve.class};
  private static Random rand = new Random(47);
  private int size = 0;
  public CoffeeGenerator() {
  }

  public CoffeeGenerator(int size) {
    this.size = size;
  }

  /**
   * 随机生成一个咖啡实例
   * @return 咖啡
   */
  @Override
  public Coffee next() {
    try {
      return (Coffee)types[rand.nextInt(types.length)].getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  class CoffeeIterator implements Iterator<Coffee> {
    int count = size;   // 数量为size个数
    @Override
    public boolean hasNext() {
      return count > 0;
    }

    @Override
    public Coffee next() {
      count--;
      return CoffeeGenerator.this.next(); // 该实例化对象的next()方法
    }
  }

  @Override
  public Iterator<Coffee> iterator() {
    return new CoffeeIterator();
  }

  public static void main(String[] args) {
    CoffeeGenerator gen = new CoffeeGenerator(5);
    System.out.println(gen.next());
    System.out.println(gen.next());
    System.out.println(gen.next());
    System.out.println(gen.next());
    System.out.println(gen.next());
    System.out.println(gen.next());
    // 迭代器
    Iterator<Coffee> iterator = gen.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
